// ==UserScript==
// @name        YE功能增强.99 - [All In One]
// @description 大型混合型脚本，一个脚本中匹配各种需要添加少量脚本的网站的合集脚本
// @namespace   http://AsionTang.CN
// @copyright   2015+, AsionTang
// @author      AsionTang
// @version     240618.22.02.078
// @iconURL     http://g.cn/favicon.ico
// @run-at      document-start
// @downloadURL https://gitee.com/AsionTang/52.ScriptLibrary/raw/master/YeJS/99.YeAllInOne.user.js
// @require     https://gitee.com/AsionTang/52.ScriptLibrary/raw/master/YeJS/00.Utils.js
// @require     https://gitee.com/AsionTang/52.ScriptLibrary/raw/master/YeJS/00.Utils.SuiShouJi.js
// @match       *://www.0daydown.com/*
// @match       *://www.echangyun.com/*
// @match       *://www.echangyun.cn/*
// @match       *://www.58chedai.com/*
// @match       *://*.kaola.com/*
// @match       *://*.xwsd.com/*
// @match       *://*.jd.com/*
// @match       *://*.jd.cn/*
// @match       *://*.jd.com.hk/*
// @match       *://*.amazon.com/*
// @match       *://*.amazon.cn/*
// @match       *://*.dida365.cn/*
// @match       *://*.dida365.com/*
// @match       *://dida365.com/*
// @match       *://*.qunar.com/*
// @match       *://*.qunar.cn/*
// @match       *://*.feidee.com/*
// @match       *://*.sui.com/*
// @match       *://*.aotu40.com/*
// @match       *://*.aotu42.com/*
// @match       *://*.avaotu.net/*
// @match       *://*.avaotu.com/*
// @match       *://*.etao.com/*
// @match       *://zhiyou.smzdm.com/guanzhu/daren*
// @match       *://zhiyou.smzdm.com/guanzhu/biaoqian*
// @match       *://photo.163.com/*
// @match       *://mp.weixin.qq.com/*
// @match       *://*.iconfont.cn/*
// @match       https://www.zrfan.com/blog/latest
// @match       https://www.kujiale.com/pcenter/design/*/list
// @grant       GM_openInTab
// @grant       GM_setClipboard
// ==/UserScript==

//================================================================
// 参考资料:
//     CSS Selectors Reference
//     https://www.w3schools.com/cssref/css_selectors.asp
//================================================================
var YE_IS_DEBUG = false;

(function() {
    if (!isLocationHrefContainsAll('kujiale.com'))
        return;
    //================================================================================
    console.log("019.给酷家乐的任意渲染图增加设置为封面的功能按钮");
    //================================================================================
    window.Ye_019_setIntervalId = setInterval(function() {
        document.onclick = document_onclick;
        document_onclick();
    }, 1000);
    document.onclick = document_onclick;

    function document_onclick() //
    {
        //clearInterval(window.Ye_019_setIntervalId);
        let rows = document.querySelectorAll('.J_singleDownload');
        for (let row of rows) {
            row.innerText = '设置为封面';
            row.onclick = function(e) {
                clearInterval(window.Ye_019_setIntervalId);
                e.stopPropagation();
                var xhr = new XMLHttpRequest();
                xhr.open('PUT', 'https://www.kujiale.com/design-manage/api/design/pic/edit');
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        alert(xhr.responseText);
                    } else {
                        console.error('Request failed, status code: ' + xhr.status);
                        console.error('Error message: ' + xhr.statusText);
                        console.error('Error responseText: ' + xhr.responseText);
                        alert('返回状态码非200!');
                    }
                }
                xhr.onerror = function(event) {
                    console.error('Request error');
                    console.error('Error details:', event);
                    alert('请求出现异常!');
                }
                xhr.send(JSON.stringify({
                    "obsDesignId": unsafeWindow.g_kjl.serverData.basicInfo.obsDesignId,
                    "obsCoverPicId": row.closest('li:not(.J_singleDownload)').dataset.picid
                }));
            }
        }
        console.log(`已经给${rows.length}个图片增加了"设置为封面"按钮`);
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('www.zrfan.com/blog/latest'))
        return;
    //================================================================================
    console.log("018.增加了每日最新页面");
    //================================================================================
    var whiteList = ['招商', '交通', '农业', '浦发', '工商', '银联', '云闪付', '建设', '龙支付', '建行', '兴业'];
    var blackListHuoDong = ['加油', '饿了么', '饭票', '12306', '星巴克', '外卖', '分期', '积分抢', '网约车', '生日特权', '瑞幸', '口碑', '来伊份', '特邀', '抽红包', '口红', '爱购月月刷', '本来生活'//
    , '浦发信用卡', '浦发苏宁联名卡'//
    , '农行信用卡', '农业银行信用卡', '666积分抽奖', '优惠购买肯德基'];

    createIframe(0, 'https://www.zrfan.com/blog/', window.innerWidth, window.innerHeight, function(e) //
    {
        var aframe = e.currentTarget;
        var newItem = aframe.contentWindow.document.querySelector('#main > article > .entry-more > a');
        if (newItem) //
        {
            createIframe(779, newItem.href, window.innerWidth, window.innerHeight, function(e) //
            {
                var aframe = e.currentTarget;
                setTimeout(function() {
                    removeNodes(aframe.contentWindow.document)
                }, 1000);
            }, 100000, null);
        }
    }, 100000, null);
    function removeNodes(document) {
        document.querySelector(".fancybox").style.display = 'none';

        var needDeleteItems = [];
        var items = document.getElementsByTagName('span');
        for (var i = 0; i < items.length; i++) //
        {
            var item = items[i];
            if (!item.attributes.style)
                continue;
            //color: #800000;
            if (item.attributes.style.value.indexOf('color: #800000;') == -1)
                continue;

            var isMached = false;
            for (var j = 0; j < whiteList.length; j++)
                if (item.innerText.indexOf(whiteList[j]) > -1) {
                    isMached = true;
                    break;
                }

            var p = getParentElementByTagName(item, 'blockquote');
            if (!p) {
                p = getParentElementByTagName(item, 'p');
                if (!p)
                    continue;
            }

            //银行白名单匹配时
            if (isMached) //
            {
                //还需要看是否在活动黑名单
                var isMachedHuoDong = false;
                for (var z = 0; z < blackListHuoDong.length; z++)
                    if (p.innerText.indexOf(blackListHuoDong[z]) > -1) //
                    {
                        isMachedHuoDong = true;
                        break;
                    }
                //只有不在黑名单的才逃过一劫.
                if (!isMachedHuoDong)
                    continue;
            }

            //终极劫难: 被隐藏或移除
            //p.style.display = 'none';
            needDeleteItems.push(p);
        }
        for (var p of needDeleteItems)
            p.parentElement.removeChild(p);
    }

    /**
 * 一直向上获取指定Tag标签的父节点
 */
    function getParentElementByTagName(e, tagName) //
    {
        if (e.tagName.toUpperCase() == tagName.toUpperCase())
            return e;
        if (e.parentElement == null)
            return null;
        return getParentElementByTagName(e.parentElement, tagName);
    }
    function createIframe(id, url, width, height, onLoadCallback, timeOut, timeOutCallback) {
        var timeOutVar = setTimeout(function() {
            clearTimeout(timeOutVar);
            timeOutCallback.apply(this, arguments);
            return;
        }, timeOut);
        var iframe = document.createElement("iframe");
        iframe.id = id;
        iframe.width = width;
        iframe.height = height;
        iframe.src = url;
        if (iframe.attachEvent) {
            iframe.attachEvent("onload", function() {
                clearTimeout(timeOutVar);
                onLoadCallback.apply(this, arguments);
            });
        } else {
            iframe.onload = function() {
                clearTimeout(timeOutVar);
                onLoadCallback.apply(this, arguments);
            }
        }
        //document.body.appendChild(iframe);
        //document.appendChild(iframe);
        //document.write(iframe.outerHTML)
        document.firstElementChild.prepend(iframe);
        return iframe;
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('iconfont.cn'))
        return;
    //================================================================================
    console.log("017.Iconfont-阿里巴巴矢量图标库 自动增加图标背景方便挑选");
    //================================================================================
    window.Ye_017_setIntervalId = setInterval(function() {
        document.onclick = document_onclick;
    }, 1000);
    document.onclick = document_onclick;

    function document_onclick() //
    {
        clearInterval(window.Ye_017_setIntervalId);
        document.querySelector('.download-dialog .mp-e2e-body .download-content .left-stage-container .stage .icon').style.backgroundColor = 'blue';
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('weixin.qq.com'))
        return;
    //================================================================================
    console.log("016.微信公众号文章标题修复");
    //================================================================================
    window.Ye_016_setIntervalId = setInterval(function() {
        document.onclick = document_onclick;
    }, 1000);
    document.onclick = document_onclick;

    function document_onclick() //
    {
        clearInterval(window.Ye_016_setIntervalId);
        if (document.title.indexOf('|') == -1)
            document.title = document.getElementById('activity-name').innerText + ' | ' + document.title;
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('photo.163.com'))
        return;
    //================================================================================
    console.log("015.网易相册一键修改相册权限为公开");
    //================================================================================
    window.Ye_015_setIntervalId = setInterval(function() {
        document.ondblclick = document_onclick;
    }, 1000);
    document.ondblclick = document_onclick;

    function document_onclick() //
    {
        doit();
    }

    function sleep(ms) {
        return new Promise(resolve=>setTimeout(resolve, ms));
    }
    async function doit() {
        var items = document.querySelectorAll('#photo-163-com-container div > .item');
        console.log('相册数量:' + items.length);
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var type = item.querySelector('.ztag201008041230345 .r');
            if (type.innerText.indexOf('私人') == -1)
                continue;

            //输出相册名称.
            console.log(item.innerText);

            //1.找到相册编辑按钮
            var btn = item.querySelector('.t-a.ztag201008041230345');
            if (btn.title.indexOf('编辑') == -1) {
                console.error('已经无法通过样式 .t-a.ztag201008041230345 来找到 编辑 按钮了.')
                break;
            }
            btn.click();

            //2.需要延迟一直等待对话框弹出来.
            while (true) {
                var rdbPublic = document.querySelector('#photo-163-com form label input[type="radio"]');
                if (!rdbPublic) {
                    console.log('sleep 1s');
                    await sleep(1000);
                    continue;
                } else {
                    rdbPublic.click();
                    break;
                }
            }

            //3.点击确认按钮。
            var btnSure = document.querySelector('#photo-163-com form div button');
            if (btnSure.innerText.indexOf('确定') == -1) {
                console.error('已经无法通过样式 photo-163-com form div button 来找到 确定 按钮了.')
                break;
            }
            btnSure.click();
            console.log('点击成功.休息1s');

            await sleep(1000);
        }
        console.log('全部执行完毕.');
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('zhiyou.smzdm.com', 'guanzhu', 'daren') && !isLocationHrefContainsAll('zhiyou.smzdm.com', 'guanzhu', 'biaoqian'))
        return;
    //================================================================================
    console.log("014.SMZDM 自动取消关注");
    //================================================================================
    window.Ye_014_setIntervalId = setInterval(function() {
        document.ondblclick = document_onclick;
    }, 1000);
    document.ondblclick = document_onclick;

    function document_onclick() //
    {
        if (localStorage.getItem('YeAutoUnFocusEnabled') === 'true') {
            console.log('当程序已经启动时,将其置为不启用');
            localStorage.removeItem('YeAutoUnFocusEnabled');
        } else {
            console.log('开始启动程序.');
            localStorage.setItem('YeAutoUnFocusEnabled', 'true');
            startUnFocus();
        }
    }

    //每次启动时,判断是否要自动启动程序.
    if (localStorage.getItem('YeAutoUnFocusEnabled') === 'true') {
        console.log('自动开始启动程序.');
        startUnFocus();
        return;
    }

    function startUnFocus() {
        var items = document.querySelectorAll('#feed-main .focus-btn.J_user_focus');
        console.log('检测到需要取消的数量=' + items.length);
        if (items.length === 0)
            setTimeout(startUnFocus, 1000);

        for (var i = 0; i < items.length; i++) {
            //[原来JavaScript的闭包是这么回事！ - 前端之巅](https://mp.weixin.qq.com/s?__biz=MzUxMzcxMzE5Ng==&mid=2247489446&idx=1&sn=a3d5440b8d7a332cd9f98644437c0ead&chksm=f951a2e5ce262bf3cbf1f742326529f6a77cfff660f3bcb0f94d741682bc290de2fa498bf8c0&mpshare=1&scene=1&srcid=0902IVZLBonQBZVW7foi2dqR#rd)
            function cx(index, i) {
                return function() {
                    console.log(i.innerText);
                    i.click();

                    //当最后一个取消关注完毕后,假如还要继续,就刷新一下当前页面.
                    if (index === 19 && localStorage.getItem('YeAutoUnFocusEnabled') === 'true') {
                        console.log('2.5秒后自动刷新');
                        setTimeout(function() {
                            location.reload();
                        }, 2500);
                    }
                }
            }
            setTimeout(cx(i, items[i]), 2500 * (i + 1));
        }
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('etao.c'))
        return;
    //================================================================================
    console.log("013.etao");
    //================================================================================

    //对所有产品重新排序
    window.Ye_013_setIntervalId = setInterval(function() {
        document.onclick = document_onclick;
    }, 1000);
    document.onclick = document_onclick;

    function document_onclick() //
    {
        clearInterval(window.Ye_013_setIntervalId);

        console.log("013.etao");

        var items = document.querySelectorAll('#J_content tr');
        for (var i = 0; i < items.length; i++)
            items[i].ondblclick = ondblclick;
    }

    function ondblclick(e) //
    {
        var row = getParentElementByTagName(e.srcElement, 'tr');

        //下单时间
        var time = /(2\d{3}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/.exec(row.children[0].innerText)[0];
        console.dir(time);

        //总价
        var totalAccount = toNumber(row.children[1].innerText);

        //购物名称
        var memo = toPureName(row.children[0].innerText);
        memo = memo.replace(/订单号.+/, '');
        memo = '【' + time.substr(0, 10) + '淘宝网购￥' + toFixedEx(totalAccount, 2) + '】' + memo;

        console.dir(memo);

        //返利
        var price = toFixedEx((toNumber(row.children[2].innerText) / 100), 2);
        console.dir(price);

        //集分宝
        var category = "1770193159158";
        //也支付宝
        var account = "15416986541";

        //保存
        saveIncomeRecord(category, account, price, time, memo);
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('jd.c', 'search'))
        return;
    //================================================================================
    console.log("012.京东优化");
    //================================================================================

    function injectCss() {
        var css = [''//
        , ".p-name { height: auto !important; }"// 让搜索商品列表的名称显示更完整.
        , ".p-name em, .p-name i{ height: auto !important; }"// 让搜索商品列表的促销文本显示更完整.
        , ""].join("\n");

        var node = document.createElement("style");
        node.type = "text/css";
        node.appendChild(document.createTextNode(css));
        var heads = document.getElementsByTagName("head");
        if (heads.length > 0) {
            heads[0].appendChild(node);
        } else {
            // no head yet, stick it whereever
            document.documentElement.appendChild(node);
        }
    }
    injectCss();
    //对所有产品重新排序
    window.Ye_012_setIntervalId = setInterval(function() {
        document.onclick = document_onclick;
    }, 1000);
    document.onclick = document_onclick;

    function document_onclick() //
    {
        clearInterval(window.Ye_012_setIntervalId);

        var ux = [];

        //获取所有的产品
        var items = document.querySelectorAll('#plist .gl-item');
        for (var i = 0; i < items.length; i++) //
        {
            var li = items[i];
            var price = parseFloat(li.querySelector('.p-price i').innerText);
            var promo_words = li.querySelector('.promo-words').innerText;

            //
            var tmp = {};
            tmp.dom = li;
            tmp.price = price;
            tmp.promo_words = promo_words;
            //
            ux.push(tmp);
        }

        //对所有产品重新排序
        ux.sort(function(a, b) //
        {
            //把价格小的排最前面
            var c = a.price - b.price;
            if (c != 0)
                return c;
            //价格一样时,将有活动的显示在前
            var aHadPromo = a.promo_words && a.promo_words.length > 0;
            var bHadPromo = b.promo_words && b.promo_words.length > 0;
            if (aHadPromo && bHadPromo) //
            {
                //两个产品都有活动时,优先显示没有"此商品不参加活动"的产品.
                var aValid = a.promo_words.indexOf('不参加') == -1;
                var bValid = b.promo_words.indexOf('不参加') == -1;
                if (aValid && bValid)
                    return 0;
                if (aValid)
                    return -1;
                if (bValid)
                    return 1;
            }
            if (aHadPromo)
                return -1;
            if (bHadPromo)
                return 1;
        });

        var ul = document.querySelector('#plist ul');

        //移除原先顺序错乱的li内容
        while (ul.firstChild)
            ul.removeChild(ul.firstChild);

        //再添加排序好的li内容
        for (var j = 0; j < ux.length; j++)
            ul.appendChild(ux[j].dom);
    }
    ;
}
)();

(function() {
    if (!isLocationHrefContainsAll('aotu') && !isLocationHrefContainsAll('avaotu'))
        return;
    //================================================================================
    console.log("011.avaotu 去广告和美化，精简HTML");
    //================================================================================

    function injectCss() {
        var css = [''//
        //美化视频缩略图以表格形式展示（改为一行多张，默认是列表一行一张图，滚动查看太费劲）！
        , "li{display: inline-table;}"//
        , ""].join("\n");

        var node = document.createElement("style");
        node.type = "text/css";
        node.appendChild(document.createTextNode(css));
        var heads = document.getElementsByTagName("head");
        if (heads.length > 0) {
            heads[0].appendChild(node);
        } else {
            // no head yet, stick it whereever
            document.documentElement.appendChild(node);
        }
    }

    //精简HTML代码，方便另存为HTML时去掉广告及不需要的元素
    function removeAll() {
        removeTag('link');
        removeTag('input');
        removeTag('iframe');
        removeTag('center');
        removeTag('script');
        removeTag('style');

        removeSelector('.ads');
        removeSelector('.ads-player');
        removeSelector('center');
        removeSelector('#related');
        removeSelector('.img-thumbnail');
        removeSelector('.logo');
        removeSelector('#player-advertising');
        removeSelector('#search-form');
        removeSelector('.margin-right-left.actions-left.actions-separated.list-inline');
        removeSelector('#language-select');
        removeSelector('.dropdown > .dropdown-toggle');
        removeSelector('li:nth-of-type(4) > a[href^="http://honghua1.com/"]');

        if (document.readyState !== 'complete')
            setTimeout(removeAll, 100);
        else
            injectCss();
    }
    removeAll();

    function removeSelector(selector) {
        removeItems(function(e) {
            return document.querySelectorAll(e);
        }, selector);
    }

    function removeTag(tagName) {
        removeItems(function(e) {
            return document.getElementsByTagName(e);
        }, tagName);
    }

    function removeItems(fnGetItems, arg) {
        var items;
        do {
            items = fnGetItems(arg);
            if (items.length == 0) {
                console.log('remove all "' + arg + '" Elements finished!');
                return;
            }
            var i = 0;
            var item = items[i];
            if (!item)
                continue;
            if (!item.parentElement)
                continue;
            item.parentElement.removeChild(item);
            console.log(arg + '.index:' + items.length + '.remove ok!');
        } while (items.length > 0);
        //
        console.log('remove all "' + arg + '" Elements finished!');
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('qunar', 'flight'))
        return;
    console.log("010.在去哪儿飞机票检索列表里，自动点击“直飞”的勾选框1");
    //================================================================================
    // 010.在去哪儿飞机票检索列表里，自动点击“直飞”的勾选框
    //================================================================================
    window.Ye_010_setIntervalId = setInterval(function() {
        document.onclick = document_onclick;
        document_onclick();
    }, 1000);
    document.onclick = document_onclick;

    function document_onclick(e) {

        console.log("010.在去哪儿飞机票检索列表里，自动点击“直飞”的勾选框2");

        //当用户点击Doc时，e不为空,则此时不是自动运行的.
        var isAutoRun = e ? false : true;

        var p = document.getElementsByClassName('item item-direct')[0];
        if (!p) {
            console.error('找不到直飞按钮!');

            if (!isAutoRun)
                showToastAtTitle('找不到直飞按钮!');
            return;
        }
        p = p.getElementsByTagName('input')[0];
        if (!p) {
            console.error('找不到直飞按钮!');

            if (!isAutoRun)
                showToastAtTitle('找不到直飞按钮!');
            return;
        }
        if (p.checked) {
            console.log('直飞按钮已经选中!');
            clearInterval(window.Ye_010_setIntervalId);
            return;
        }

        p.click();
        {
            console.log('直飞按钮选中完毕!');
            return;
        }
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('dida365'))
        return;
    console.log("009.在dida365滴答清单里支持快速入账1");
    function injectCss() {
        var css = [''//
        , "#root, body, html { font-family: inherit !important; }"// 恢复默认字体
        ].join("\n");

        var node = document.createElement("style");
        node.type = "text/css";
        node.appendChild(document.createTextNode(css));
        var heads = document.getElementsByTagName("head");
        if (heads.length > 0) {
            heads[0].appendChild(node);
        } else {
            // no head yet, stick it whereever
            document.documentElement.appendChild(node);
        }
    }
    injectCss();
    //================================================================================
    // 009.在dida365滴答清单里支持快速入账
    //================================================================================
    window.Ye_009_setIntervalId = setInterval(function() {
        document.onclick = document_onclick;
        document.ondblclick = document_onclick;
    }, 1000);

    function document_onclick() {
        clearInterval(window.Ye_009_setIntervalId);

        //================================================================================
        console.log(`YEYEYE:21:绑定点击"文件夹"ICON图标时,触发快速设置分组的功能`);
        //================================================================================
        {
            document.querySelectorAll("#td-footer .project-setting").forEach(e=>e.onclick = onProjectSettingClick);

            function onProjectSettingClick(e) {
                //因为SVG控件不支持触发Click事件,所以只能通过e.offsetX坐标进行判断用户点击的是否在SVG图标范围.
                if (e && e.offsetX > 24)
                    return;

                let other = document.querySelector(".project-menu li:last-child a > div");
                if (!other) {
                    retry(`YEYEYE:找不到 其它分组!重试中`);
                    return;
                }
                //直接Click居然无效!很奇怪!
                //NO:other.click();

                // other.focus();
                other.dispatchEvent(new MouseEvent('mouseover',{
                    bubbles: true,
                    cancelable: true
                }));

                for (let i of document.querySelectorAll(".dropdown-menu-menu-submenu li")) {
                    if ('软件收藏夹' == i.innerText) {
                        i.click();
                        console.log(`YEYEYE:快速设置 软件收藏夹 分组 成功!`);
                        return;
                    }
                }
                retry(`YEYEYE:找不到 二级分组!重试中`);
            }
            let lastError = null;
            let lastErrorRetryCount = 0;
            let lastErrorTime = 0;
            let lastTimeoutId = 0;
            function retry(err) {
                let now = Date.now();
                if (lastError !== err || now - lastErrorTime > 2000) {
                    clearTimeout(lastTimeoutId);
                    lastErrorRetryCount = 0;
                    lastErrorTime = now;
                }
                lastError = err;
                lastErrorRetryCount++;
                if (lastErrorRetryCount > 10) {
                    console.log(err + "\t 重试次数超过阈值已停止!=" + lastErrorRetryCount);
                    return;
                }
                console.log(err + "\t 重试次数=" + lastErrorRetryCount);
                lastTimeoutId = setTimeout(onProjectSettingClick, 100);
            }
        }
        //================================================================================
        console.log(`YEYEYE:20:绑定点击"日历"ICON图标时,触发特殊处理逻辑`);
        //================================================================================
        {
            document.querySelectorAll('#quick-set').forEach(e=>e.onclick = f2);

            function f2() {
                console.log(`YEYEYE:2:检测到特殊按钮点击事件,延迟触发后续功能!`);
                setTimeout(f3, 100);
            }
            function f3() {
                let time = document.getElementById('js-timecard');
                if (!time) {
                    retry(`YEYEYE:找不到 timecard!重试中`);
                    return;
                }

                let cRepeatView = time.querySelector('.choose-repeat div.select-title');
                if (!cRepeatView) {
                    retry(`YEYEYE:找不到 cRepeatView!重试中`);
                    return;
                }

                let yuefen = document.querySelector(".freq-element .dropdown-menu-menu-root > li:nth-child(3)");
                if (!yuefen) {
                    cRepeatView.click();

                    retry(`YEYEYE:找不到 每月重复按钮!尝试点击"重复"后重试中`);
                    return;
                }
                console.log(`YEYEYE:点击 每月重复按钮 中`);
                yuefen.click()

                let nextMday = document.querySelector("#js-timecard .kalenade-day-item .bg-primary-30");
                if (!nextMday) {
                    document.querySelector('#js-timecard .k-next').click();
                    retry(`YEYEYE:找不到 下月对应日期!重试中`);
                    return;
                }
                console.log(`YEYEYE:点击 下月对应日期 按钮 中`);
                nextMday.click();

                console.log(`YEYEYE:点击 确认 按钮 中`);
                time.querySelector('#js-timecard-btns>.btn-primary').click()

                console.log(`YEYEYE:已停止定时执行任务!`);
            }
            let lastError = null;
            let lastErrorRetryCount = 0;
            let lastErrorTime = 0;
            function retry(err) {
                let now = Date.now();
                if (lastError !== err || now - lastErrorTime > 2000) {
                    lastErrorRetryCount = 0;
                    lastErrorTime = now;
                }
                lastError = err;
                lastErrorRetryCount++;
                if (lastErrorRetryCount > 10) {
                    console.log(err + "\t 重试次数超过阈值已停止!=" + lastErrorRetryCount);
                    return;
                }
                console.log(err + "\t 重试次数=" + lastErrorRetryCount);
                setTimeout(f3, 100);
            }
        }

        //====================================================================
        console.log("009.在dida365滴答清单里支持快速入账2");

        var items = document.querySelectorAll('#task-list-content li');
        for (var i = 0; i < items.length; i++)
            items[i].ondblclick = ondblclick;

        function ondblclick(e) {
            //====================================================================
            // 业务代码区
            //====================================================================
            var tasktitle = document.querySelector('#tasktitle');
            tasktitle = tasktitle.innerText.trim();
            if (tasktitle.indexOf('记账') == -1) {
                showToastAtTitle('点击了不在预期范围内的行数据:' + tasktitle);
                console.log('点击了不在预期范围内的行数据:' + tasktitle);

                let taskid = e.currentTarget.attributes.taskid.value;
                console.log('获取详情taskid=' + taskid);
                getTaskByTaskId(taskid).catch((error)=>console.error(error)).then((task)=>whenGetTask(task));
                function whenGetTask(task) {
                    let needCopyText = new Date(task.createdTime).toLocaleString() + '\n' + (task.content?task.content:task.title);
                    console.log(needCopyText);
                    var data = {
                        "toUser": "AsionTang@163.com",
                        "code": "lLLSsRKhEd",
                        "data": needCopyText,
                        "operation": "action",
                        "action": "a0fc8e2d-7943-40d1-becd-95d480e8b646",
                        // 标题:记账脚本
                    }
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', 'https://push.getquicker.cn/to/quicker', true);
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    xhr.send(JSON.stringify(data));
                }
                async function getTaskByTaskId(taskId) {
                    return new Promise((resolve,reject)=>{
                        const request = indexedDB.open('localdatabase');
                        request.onerror = (event)=>reject(event.target.error);
                        request.onsuccess = (event)=>{
                            const db = event.target.result;
                            const transaction = db.transaction('tasks', 'readonly');
                            const objectStore = transaction.objectStore('tasks');
                            const geter = objectStore.get(taskId);
                            geter.onerror = (event)=>reject(event.target.error);
                            geter.onsuccess = (event)=>resolve(event.target.result);
                        }
                    }
                    );
                }
                return;
            }
            var jiZhangRecordsStr;
            if (tasktitle.startsWith('记账地铁云闪付') || tasktitle.startsWith('记账云闪付地铁')) {
                var items = tasktitle.split(' ');
                if (items.length !== 6) {
                    showToastAtTitle('格式不对,应该为5个空格:' + tasktitle);
                    console.log('格式不对,应该为5个空格:' + tasktitle);
                    return;
                }
                items = items.slice(1);

                var date = items[0];

                var time1 = items[1];
                var time2 = items[3];

                var price1 = items[2];
                var price2 = items[4];

                var youhui1 = 4 - parseFloat(price1);
                var youhui2 = 4 - parseFloat(price2);

                jiZhangRecordsStr = `
${date} ${time1}
上海地铁;云闪付APP;支付有优惠;
收入 优惠 暂付金 ${youhui1.toFixed(2)}
转账 也沃尔玛 暂付金 ${price1}
支出 地铁 暂付金 4


${date} ${time2}
上海地铁;云闪付APP;支付有优惠;
收入 优惠 暂付金 ${youhui2.toFixed(2)}
转账 也沃尔玛 暂付金 ${price2}
支出 地铁 暂付金 4

`;
            } else {
                var taskcontent = document.querySelector('#taskcontent');
                jiZhangRecordsStr = taskcontent.innerText.trim();
                if (jiZhangRecordsStr.length == 0) {
                    showToastAtTitle('检测到:记账数据为空');
                    console.log('检测到:记账数据为空');
                    return;
                }
            }

            var items = jiZhangRecordsStr.split('\n');
            console.dir(items);

            var currentDateTime = '';
            var currentRemark1 = '';
            var recordUrls = [];
            var lastRecordType;
            var lastAccount;
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                item = item.trim();

                //当等于空行时,则重置。开始跳过此行循环。
                //[零宽空格 - 维基百科，自由的百科全书](https://zh.wikipedia.org/wiki/零宽空格)
                if (item.length == 0 || (item.length == 1 && encodeURIComponent(item) === "%E2%80%8B")) {
                    currentDateTime = '';
                    currentRemark1 = '';
                    continue;
                    //break;
                }

                //第1行：日期（2017年11月4日|17年1月14日|20171024|171024|10-24|10.24）+空格+时间（12:00:00|12:00）
                {
                    currentDateTime = obj2DateTime(item);
                    if (currentDateTime == undefined) {
                        recordUrls = undefined;
                        showToastAtTitleAndLogError('日期时间格式有误:' + item);
                        break;
                    }
                    console.log(currentDateTime);
                }

                //第2行：备注1（此行可省略直接写第三行的格式）
                {
                    var item = items[i + 1];
                    item = item.trim();
                    //只要不是以下关键字开头的文本就当作备注。
                    if (item.search(/^收入|^支出|^转账/gm) == -1) {
                        currentRemark1 = item;
                        console.log(currentRemark1);
                        //将当前行游标设置为备注行.
                        i = i + 1;
                    }
                }
                //间隔行\n
                for (++i; i < items.length; i++) {
                    var item = items[i];
                    item = item.trim();

                    //当等于空行时,则重置。开始下一轮外循环。
                    //[零宽空格 - 维基百科，自由的百科全书](https://zh.wikipedia.org/wiki/零宽空格)
                    if (item.length == 0 || (item.length == 1 && encodeURIComponent(item) === "%E2%80%8B")) {
                        lastRecordType = undefined;
                        lastAccount = undefined;
                        currentDateTime = '';
                        currentRemark1 = '';
                        break;
                    }

                    //防止中文输入法出现特殊空格,所以统一使用\s来切割.
                    var recordItems = item.split(/\s+/gm);

                    // 支持两种记账格式
                    if (recordItems.length == 2) {
                        //类型
                        if (recordItems[0].search(/^收入$|^支出$/gm) == -1) {
                            recordUrls = undefined;
                            showToastAtTitleAndLogError('记账格式有误:' + item);
                            return;
                        }
                        //账户
                        var account = getAccount(recordItems[1]);
                        if (account == undefined) {
                            recordUrls = undefined;
                            showToastAtTitleAndLogError('账户无法识别:' + recordItems[2]);
                            return;
                        }
                        lastRecordType = recordItems[0];
                        lastAccount = account;
                        continue;
                    }
                    if (lastRecordType && lastAccount) {
                        //记账格式1:
                        //[支出|收入] [账户]
                        //[特殊符号;?等等][备注] [金额] [分类]
                        if (!processTheMoneyRecord1(recordItems))
                            //当返回False 时说明存在错误的数据无法识别.因此不再继续处理.
                            return;
                    } else {
                        //第3行：记账（[收入|支出] 分类 账户 金额 备注2|转账 转出账户 转入账户 金额 备注2）(最终备注=备注1;备注2)
                        //第N行：记账（[收入|支出] 分类 账户 金额 备注2|转账 转出账户 转入账户 金额 备注2）(最终备注=备注1;备注2)
                        if (!processTheMoneyRecord2(recordItems))
                            //当返回False 时说明存在错误的数据无法识别.因此不再继续处理.
                            return;
                    }
                }
            }

            //当被重置时,说明存在错误的数据无法识别.因此不做任何处理.
            if (recordUrls == undefined)
                return;

            if (recordUrls.length == 0) {
                showToastAtTitleAndLogError('没有解析出记账条目!');
                return;
            }

            var i = 0;

            function openUrl() {
                if (i >= recordUrls.length)
                    return;

                var url = recordUrls[i];
                if (typeof GM_openInTab !== 'undefined')
                    GM_openInTab(url, {
                        insert: false,
                        active: false
                    });
                else
                    window.open(url);

                i++;

                if (i % 3 == 0)
                    setTimeout(openUrl, 2000);
                else
                    openUrl();
            }
            openUrl();

            function processTheMoneyRecord1(recordItems) {
                //记账格式1:
                //[支出|收入] [账户]
                //[备注] [金额] [分类]
                if (recordItems.length < 3) {
                    recordUrls = undefined;
                    showToastAtTitleAndLogError('记账格式有误:' + item);
                    return false;
                }
                var price = toNumber(recordItems[recordItems.length - 2]);
                //
                if (isNaN(price)) {
                    recordUrls = undefined;
                    showToastAtTitleAndLogError('记账格式有误:' + item);
                    return false;
                }
                var time = currentDateTime;
                var memo = '';
                {
                    if (currentRemark1.length > 0) {
                        memo += currentRemark1;

                        if (currentRemark1.search(/;$|；$| $/gm) == -1)
                            memo += '；';
                    }
                    memo += recordItems.slice(0, recordItems.length - 2).join('；');
                }
                //分类
                var category = getCategory(recordItems[recordItems.length - 1]);

                if (category == undefined) {
                    recordUrls = undefined;
                    showToastAtTitleAndLogError('分类无法识别:' + recordItems[recordItems.length - 1]);
                    return false;
                }
                //开始实际入账了.
                //YE_IS_DEBUG = true;
                switch (lastRecordType) {
                case "收入":
                    {
                        saveIncomeRecord(category, lastAccount, price, time, memo, function(url) {
                            recordUrls.push(url);
                        });
                    }
                    break;
                case "支出":
                    {
                        savePayoutRecord(category, lastAccount, price, time, memo, function(url) {
                            recordUrls.push(url);
                        });
                    }
                    break;
                }
                return true;
            }

            function processTheMoneyRecord2(recordItems) {
                //记账格式2:[支出|收入|转账] [分类] [账户] [金额] [备注]
                if (recordItems.length < 4) {
                    recordUrls = undefined;
                    showToastAtTitleAndLogError('记账格式有误:' + item);
                    return false;
                }

                var recordType = recordItems[0];
                //
                if (recordType.search(/^收入$|^支出$|^转账$/gm) == -1 || !recordItems[3]) {
                    recordUrls = undefined;
                    showToastAtTitleAndLogError('记账格式有误:' + item);
                    return false;
                }
                var price = toNumber(recordItems[3]);
                //
                if (isNaN(price)) {
                    recordUrls = undefined;
                    showToastAtTitleAndLogError('记账格式有误:' + item);
                    return false;
                }

                //开始实际入账了.
                //YE_IS_DEBUG = true;
                var time = currentDateTime;
                var memo = '';
                {
                    if (currentRemark1.length > 0) {
                        memo += currentRemark1;

                        if (currentRemark1.search(/;$|；$| $/gm) == -1)
                            memo += '；';
                    }
                    memo += recordItems.slice(4).join('；');
                }
                switch (recordType) {
                case "收入":
                    {
                        //分类
                        var category = getCategory(recordItems[1]);

                        if (category == undefined) {
                            recordUrls = undefined;
                            showToastAtTitleAndLogError('分类无法识别:' + recordItems[1]);
                            return false;
                        }

                        //账户
                        var account = getAccount(recordItems[2]);
                        if (account == undefined) {
                            recordUrls = undefined;
                            showToastAtTitleAndLogError('账户无法识别:' + recordItems[2]);
                            return false;
                        }

                        saveIncomeRecord(category, account, price, time, memo, function(url) {
                            recordUrls.push(url);
                        });
                    }
                    break;
                case "支出":
                    {
                        //分类
                        var category = getCategory(recordItems[1]);
                        if (category == undefined) {
                            recordUrls = undefined;
                            showToastAtTitleAndLogError('分类无法识别:' + recordItems[1]);
                            return false;
                        }

                        //账户
                        var account = getAccount(recordItems[2]);
                        if (account == undefined) {
                            recordUrls = undefined;
                            showToastAtTitleAndLogError('账户无法识别:' + recordItems[2]);
                            return false;
                        }

                        savePayoutRecord(category, account, price, time, memo, function(url) {
                            recordUrls.push(url);
                        });
                    }
                    break;
                case "转账":
                    {
                        var category = "0";

                        //转出账户
                        var out_account = getAccount(recordItems[1]);
                        if (out_account == undefined) {
                            recordUrls = undefined;
                            showToastAtTitleAndLogError('账户无法识别:' + recordItems[1]);
                            return false;
                        }

                        //转入账户
                        var in_account = getAccount(recordItems[2]);
                        if (in_account == undefined) {
                            recordUrls = undefined;
                            showToastAtTitleAndLogError('账户无法识别:' + recordItems[2]);
                            return false;
                        }

                        var account = in_account + "-" + out_account;
                        saveTransferRecord(category, account, price, time, memo, function(url) {
                            recordUrls.push(url);
                        });
                    }
                    break;
                }
                return true;
            }
        }
    }
}
)();

(function() {
    if (isLocationHrefContainsAll('amazon', 'your-account', 'order-history')) //
    {
        //================================================================================
        console.log("008.提取Amazon订单对应的产品信息");
        //================================================================================
        window.Ye_008_setIntervalId = setInterval(function() //
        {
            document.onclick = document_onclick;
        }, 1000);
        document.onclick = document_onclick;

        function document_onclick() //
        {
            clearInterval(window.Ye_008_setIntervalId);

            var items = document.querySelectorAll('#ordersContainer .order-info .a-col-right .value');
            var aLinks = document.querySelectorAll('#ordersContainer .shipment .a-row > a[href*=oh_aui_detailpage]');
            console.log('订单总数:' + items.length);
            for (var i = 0; i < items.length; i++) //
            {
                var orderNo = items[i].innerText;
                var productName = aLinks[i].innerText;

                console.log('订单编号:' + orderNo + ' 产品名称:' + productName);

                //见订单编号里的所有产品名称存入localStorage方便其它界面获取使用.
                localStorage.setItem('Ye.ProductName.' + orderNo, productName);
            }

            //================================================================================
            console.log("008.点击产品记录支出");
            //================================================================================
            var items = document.querySelectorAll('#ordersContainer .shipment');
            for (var i = 0; i < items.length; i++)
                items[i].ondblclick = ondblclick;

            function ondblclick(e) //
            {
                console.dir(e);
                var order = getParentElementByClassName(e.srcElement, 'order');
                var eTime = order.querySelector('.order-info .a-row > .value');
                var time = toPureDateTime(eTime.innerText.replace(/年(\d)月/gm, '年0$1月').replace(/月(\d)日/gm, '月0$1日').replace(/年/gm, '-').replace(/月/gm, '-').replace(/日/gm, ''));
                console.dir(time);

                var container = getParentElementByClassName(e.srcElement, 'a-fixed-right-grid-col a-col-left');
                console.dir(container);

                var eName = container.querySelector('.a-row > a[href*=oh_aui_detailpage]');
                console.dir(eName.innerText);

                var ePrice = container.querySelector('.a-row > span.a-color-price');
                console.dir(ePrice.innerText);

                //售价（记支出）
                var price = toNumber(ePrice.innerText);

                var memo = '';
                memo += '【' + time.substr(0, 10) + '亚马逊网购】';
                memo += '订单编号:' + orderNo;
                memo += ' 产品名称:' + eName.innerText;
                memo = memo.replace(/\.00/gm, '');

                //猜测支出分类
                var category = getPayoutCategoryByGuess(memo);

                var count = toNumber('1');

                //从各种暂付金支出
                var account = "15654917756";

                //统一记录为:当月最后一日的支出，并设置为猜测的分类，从各种暂付金支出。
                savePayoutRecord(category, account, price * count, getTheLastSecondDateTimeOfMonth(time), memo);
            }
            /**
             * 一直向上获取指定ClassName标签的父节点
             */
            function getParentElementByClassName(e, className) //
            {
                if (e.className.toUpperCase().indexOf(className.toUpperCase()) > -1)
                    return e;
                if (e.parentElement == null)
                    return null;
                return getParentElementByClassName(e.parentElement, className);
            }
        }
    }//
    else if (isLocationHrefContainsAll('amazon', 'payment', 'history')) //
    {
        //================================================================================
        console.log("008.记录 Amazon 整个订单 转账到 各种暂付金 记录.");
        //================================================================================
        window.Ye_008_setIntervalId = setInterval(function() //
        {
            document.onclick = document_onclick;
        }, 1000);
        document.onclick = document_onclick;

        function document_onclick() //
        {
            var items = document.querySelectorAll('#payment-history-content .a-row tr');
            for (var i = 1; i < items.length; i++)
                items[i].ondblclick = ondblclick;

            function ondblclick(e) //
            {
                var tr = getParentElementByTagName(e.srcElement, 'TR');

                var time = tr.children[0].innerText;
                var price = toNumber(tr.children[2].innerText);

                var orderNo = tr.children[1].innerText;
                var productName = localStorage.getItem('Ye.ProductName.' + orderNo);

                //备注
                var memo = '';
                memo += '【' + time.substr(0, 10) + '亚马逊网购￥' + price + '】';
                memo += ' 订单编号:' + orderNo;
                memo += ' 产品名称:' + productName;
                memo = memo.replace(/\.00/gm, '');

                //记录整订单转账到 各种暂付金 记录.
                saveTotalAccount(time, price, memo);

                function saveTotalAccount(time, totalAccount, memo) //
                {
                    console.log(memo);

                    var category = "0";

                    //默认从沃尔玛卡转账到各种暂付金
                    var in_account = "15654917756";

                    //判断今日离谁的账单日最长,就用谁.
                    var out_account = getBestOutAccountByTime(time);

                    var account = in_account + "-" + out_account;
                    var price = totalAccount;
                    saveTransferRecord(category, account, price, time, memo);
                }

                //猜测支出分类
                var category = getPayoutCategoryByGuess(memo);

                var count = toNumber('1');

                //从各种暂付金支出
                var account = "15654917756";

                //统一记录为:当月最后一日的支出，并设置为猜测的分类，从各种暂付金支出。
                savePayoutRecord(category, account, price * count, getTheLastSecondDateTimeOfMonth(time), memo);
            }
        }
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('jd', 'details', 'orderid', 'item', 'orderid'))
        return;
    console.log("007.在JD订单详情页支持双击快速录入账单 1");
    //================================================================================
    // 007.在JD订单详情页支持双击快速录入账单
    //================================================================================
    window.Ye_007_setIntervalId = setInterval(function() {
        document.onclick = document_onclick;
    }, 1000);
    document.onclick = document_onclick;

    function document_onclick() {
        clearInterval(window.Ye_007_setIntervalId);

        console.log("007.在JD订单详情页支持双击快速录入账单 2");

        //下单时间
        var time = toPureDateTime(document.querySelector('#track_time_0').innerText);

        //支付总金额
        var totalAccount = document.querySelector('.goods-total .ftx-01 .count').innerText;
        totalAccount = toNumber(totalAccount);

        //订单总的付款信息
        var payInfo = '';
        {
            var items = document.querySelectorAll('#pay-info .dd .item');
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                //排除付款信息里的不需要记录的数据.
                if (item.innerText.indexOf('付款方式') != -1//
                || item.innerText.indexOf('时间') != -1//
                || item.innerText.indexOf('¥0.00') != -1//
                )
                    continue;
                payInfo += item.innerText.replace(/\.00/gm, '').replace(/： /gm, '');
            }
        }

        //订单里的所有产品信息
        var allProductInfo = '';

        //Index头 = 标头
        //Index尾 = J-yunfeixian
        var items = document.querySelectorAll('.goods-list tr');
        for (var i = 1; i < items.length - 1; i++) {
            items[i].ondblclick = tr_ondblclick;
            allProductInfo += '|' + toPureName(items[i].children[1].innerText);
        }

        function tr_ondblclick(e) {
            var tr = getParentElementByTagName(e.srcElement, 'TR');

            //备注
            var memo = '';
            {
                memo += '【' + time.substr(0, 10) + '京东网购￥' + totalAccount + '】';

                memo += payInfo;

                saveTotalAccountOnceOnly(time, totalAccount, memo);

                memo += ' 名称：' + toPureName(tr.children[1].innerText);
                memo += ' 售价：' + tr.children[3].innerText;
                memo += ' 数量：' + tr.children[4].innerText;
                memo = memo.replace(/\.00/gm, '');
                memo = memo.replace(/\n/gm, '');

                console.log(memo);
            }

            //猜测支出分类
            var category = getPayoutCategoryByGuess(memo);

            //售价（记支出）
            var price = toNumber(tr.children[3].innerText);
            var count = toNumber(tr.children[4].innerText);

            //从各种暂付金支出
            var account = "15654917756";

            //统一记录为:当月最后一日的支出，并设置为猜测的分类，从各种暂付金支出。
            savePayoutRecord(category, account, price * count, getTheLastSecondDateTimeOfMonth(time), memo);
        }

        function saveTotalAccountOnceOnly(time, totalAccount, memo) {
            //每次打开页面只会触发一次,总订单的转账记录动作.
            if (window.Ye_isHadSaveTotalAccountRecord)
                return;
            window.Ye_isHadSaveTotalAccountRecord = true;

            memo += allProductInfo;
            memo = memo.replace(/\n/gm, '');
            console.log(memo);

            var category = "0";

            //默认从沃尔玛卡转账到各种暂付金
            var in_account = "15654917756";

            //判断今日离谁的账单日最长,就用谁.
            var out_account = getBestOutAccountByTime(time);

            var account = in_account + "-" + out_account;
            var price = totalAccount;
            saveTransferRecord(category, account, price, time, memo);
        }
    }
}
)();
(function() {
    if (!isLocationHrefContainsAll('xwsd', 'account/logs'))
        return;
    //================================================================
    // 006.小微时贷 支持双击明细自动录入到随手记
    //================================================================
    console.log("006.小微时贷 支持双击明细自动录入到随手记");
    document.onclick = function() {
        var items = document.getElementsByTagName('tr');
        for (var i = 1; i < items.length; i++)
            items[i].ondblclick = ondblclick;

        function ondblclick(e) {
            //====================================================================
            // 业务代码区
            //====================================================================
            var tr = getParentElementByTagName(e.srcElement, 'TR');

            var time = tr.children[0].innerText;
            var price = toNumber(tr.children[2].innerText);
            var memo = tr.children[3].innerText;

            console.log(memo);
            if (memo.indexOf('本金') != -1) {
                //应收 本金(计转账)

                var category = "0";
                //小微时贷-余额
                var in_account = "244709476";
                //小微时贷-定期
                var out_account = "244709474";

                var account = in_account + "-" + out_account;
                saveTransferRecord(category, account, price, time, memo);

            } else if (memo.indexOf('服务费') != -1) {
                //应收 服务费(计支出)

                //服务费
                var category = "346449537";
                //小微时贷-余额
                var account = "244709476";

                savePayoutRecord(category, account, price * -1, time, memo);

            } else if (memo.indexOf('利息') != -1) {
                //应收 利息(计收入)

                //利息
                var category = "175369647418";
                //小微时贷-余额
                var account = "244709476";

                saveIncomeRecord(category, account, price, time, memo);

            } else {
                showToastAtTitle('点击了不在预期范围内的行数据:' + tr.innerText);
                console.log('点击了不在预期范围内的行数据:' + tr.innerText);
                console.dir(tr);
            }
        }
    }
}
)();
(function() {
    if (!isLocationHrefContainsAll('kaola', 'order_detail.html'))
        return;
    //================================================================
    // 005.网易考拉 支持双击明细自动录入到随手记
    //================================================================
    console.log("005.网易考拉 支持双击明细自动录入到随手记");
    document.onclick = document_onclick;

    function document_onclick() {
        //====================================================================
        // 商品信息列表 双击记录支出
        //====================================================================

        var allProductInfo = '';

        var items = document.querySelectorAll('#docContent .j-gitem');
        for (var i = 1; i < items.length; i++) {
            items[i].ondblclick = ondblclick;

            allProductInfo += ' ' + items[i].children[1].innerText;
        }

        function saveTotalAccount(time, totalAccount, memo) {
            //每次打开页面只会触发一次,总订单的转账记录动作.
            if (window.Ye_isHadSaveTotalAccountRecord)
                return;
            window.Ye_isHadSaveTotalAccountRecord = true;

            memo += allProductInfo;
            console.log(memo);

            var category = "0";

            //默认从沃尔玛卡转账到各种暂付金
            var in_account = "15654917756";

            //判断今日离谁的账单日最长,就用谁.
            var out_account = getBestOutAccountByTime(time);

            var account = in_account + "-" + out_account;
            var price = totalAccount;
            saveTransferRecord(category, account, price, time, memo);
        }

        function ondblclick(e) {
            var tr = getParentElementByTagName(e.srcElement, 'TR');

            //下单时间
            var time = document.querySelector('#docContent .oddetail .cnt p:last-child').innerText;
            time = time.replace(/[^\d\- :]/gm, '');

            //支付总金额
            var totalAccount = document.querySelector('#docContent .oddetail .cnt p > .cred').innerText;
            totalAccount = toNumber(totalAccount);

            //备注
            var memo = '';
            {
                memo += '【' + time.substr(0, 10) + '网易考拉海购￥' + totalAccount + '】';

                var orderInfos = document.querySelectorAll('#docContent .submitWrap > div');
                var orderInfos1 = orderInfos[0];
                var orderInfos2 = orderInfos[1];
                for (var i = 0; i < orderInfos2.children.length; i++)
                    memo += ' ' + orderInfos2.children[i].innerText + orderInfos1.children[i].innerText;
                memo = memo.replace(/\.00/gm, '');

                saveTotalAccount(time, totalAccount, memo);

                memo += ' 名称：' + tr.children[1].innerText;
                memo += ' 重量：' + tr.children[2].innerText;
                memo += ' 售价：' + tr.children[3].innerText;
                memo += ' 数量：' + tr.children[4].innerText;
                memo = memo.replace(/\.00/gm, '');

                console.log(memo);
            }

            //猜测支出分类
            var category = getPayoutCategoryByGuess(memo);

            //售价（记支出）
            var price = toNumber(tr.children[3].innerText);
            var count = toNumber(tr.children[4].innerText);

            //从各种暂付金支出
            var account = "15654917756";

            //统一记录为:当月30号的支出，并设置为【日用，保健居多】，从各种暂付金支出。
            savePayoutRecord(category, account, price * count, getTheLastSecondDateTimeOfMonth(time), memo);
        }
    }
}
)();
(function() {
    //"https://www.58chedai.com/index.php?user&q=code/borrow/gathering&status=1&page=7"
    if (!isLocationHrefContainsAll('58chedai', 'index.php'))
        return;
    //================================================================
    // 004.58车贷 支持双击明细自动录入到随手记
    //================================================================
    console.log("004.58车贷 支持双击明细自动录入到随手记");
    document.onclick = function() {
        //直接跳转到第7页(2017年6月16日 18:30:20:今日的末尾页).
        {
            //只匹配"已收款明细"页面的"尾页"索引
            if (isLocationHrefContainsAll('code/borrow/gathering&status=1')) {
                var as = document.querySelectorAll('#zh_rightside .zh_rightfenye2 a');
                for (var i = 0; i < as.length; i++)
                    if (as[i].innerText.indexOf('尾页') != -1) {
                        console.log(as[i].href);
                        var pageIndex = getNumber(/page=(\d+)/gm, as[i].href);
                        console.log(pageIndex);
                        localStorage.setItem('theLastPageNumber', pageIndex);
                        break;
                    }
            }
            //默认打开第一次是第一页,然后通过读取"尾页"的索引值,记录起来,下次再打开就直接跳转到最后一页.
            var theLastPageNumber = localStorage.getItem('theLastPageNumber');
            if (!theLastPageNumber || theLastPageNumber < 1)
                theLastPageNumber = 1;
            console.log("004.58车贷 支持双击明细自动录入到随手记 Runing");

            try {
                //直接从 未收款明细 跳转到 status=1 已收款明细.
                document.querySelector('a[title="收款明细"]').href = document.querySelector('a[title="收款明细"]').href.replace('status=0', 'status=1') + '&page=' + theLastPageNumber;
            } catch (e) {}

            try {
                var href = document.getElementById('zh_rightside').getElementsByTagName('li')[1].children[0].href;
                if (href.indexOf('code/borrow/gathering') != -1)
                    document.getElementById('zh_rightside').getElementsByTagName('li')[1].children[0].href += '&page=' + theLastPageNumber;
            } catch (e) {}
        }
        //支持双击明细自动录入到随手记
        {
            var items = document.getElementById('zh_rightside').getElementsByTagName('tr');
            for (var i = 1; i < items.length; i++)
                items[i].ondblclick = ondblclick;

            function ondblclick(e) {
                //====================================================================
                // 业务代码区
                //====================================================================
                var tr = getParentElementByTagName(e.srcElement, 'TR');
                if (isLocationHrefContainsAll('code/borrow/gathering&status=1')) {
                    var time = tr.children[1].innerText;
                    var memo = tr.children[0].innerText + ' 第几期:' + tr.children[3].innerText;
                    console.log(memo);

                    //应收本金(计转账)
                    var ysBenJin = toNumber(tr.children[5].innerText);
                    if (ysBenJin > 0) {
                        console.log('应收本金:' + ysBenJin);

                        var category = "0";
                        var in_account = "251339108";
                        //58车贷-余额
                        var out_account = "251339110";

                        var account = in_account + "-" + out_account;
                        var price = ysBenJin;
                        saveTransferRecord(category, account, price, time, memo);
                    }
                    //应收利息(计收入)
                    var ysLiXi = toNumber(tr.children[6].innerText);
                    if (ysLiXi > 0) {
                        console.log('应收利息:' + ysLiXi);

                        var category = "175369647418";
                        //利息
                        var account = "251339108";
                        //58车贷-余额
                        var price = ysLiXi;
                        saveIncomeRecord(category, account, price, time, memo);
                    }
                    //应收加息(计收入)
                    var ysJiaXi = toNumber(tr.children[7].innerText);
                    if (ysJiaXi > 0) {
                        console.log('应收加息:' + ysJiaXi);

                        var category = "175369647418";
                        //利息
                        var account = "251339108";
                        //58车贷-余额
                        var price = ysJiaXi;
                        saveIncomeRecord(category, account, price, time, memo);
                    }
                } else if (isLocationHrefContainsAll('code/account/log')) {
                    var time = tr.children[7].innerText;
                    var memo = tr.children[0].innerText;
                    console.log(memo);
                    if (memo.indexOf('使用加息券收益') != -1) {
                        var category = "175369647418";
                        //利息
                        var account = "251339108";
                        //58车贷-余额
                        var price = toNumber(tr.children[1].innerText);
                        console.log('应收加息:' + price);
                        saveIncomeRecord(category, account, price, time, memo);
                    } else if (memo.indexOf('利息管理费') != -1) {
                        //把 管理费 入账
                        var category = "346449534";
                        var account = "251339108";
                        //58车贷-余额
                        var price = toNumber(tr.children[1].innerText);
                        savePayoutRecord(category, account, price, time, memo);
                    } else {
                        showToastAtTitle('点击了不在预期范围内的行数据:' + tr.innerText);
                        console.log('点击了不在预期范围内的行数据:' + tr.innerText);
                        console.dir(tr);
                    }
                } else if (isLocationHrefContainsAll('code/borrow/succes&type=wait')) {
                    //回款中的标
                    var time = tr.children[4].innerText;
                    var memo = tr.children[0].innerText;
                    console.log(memo);
                    //借出资金(计转账)
                    var jieChuZiJin = toNumber(tr.children[1].innerText);
                    if (jieChuZiJin > 0) {
                        console.log('借出资金:' + jieChuZiJin);

                        var category = "0";
                        //58车贷-余额
                        var in_account = "251339110";
                        var out_account = "251339108";

                        var account = in_account + "-" + out_account;
                        var price = jieChuZiJin;
                        saveTransferRecord(category, account, price, time, memo);
                    } else {
                        showToastAtTitle('点击了不在预期范围内的行数据:' + tr.innerText);
                        console.log('点击了不在预期范围内的行数据:' + tr.innerText);
                        console.dir(tr);
                    }
                } else {
                    showToastAtTitle('在非预期页面触发了双击:' + location.href);
                    console.log('在非预期页面触发了双击:' + location.href);
                    console.dir(tr);
                }
            }
        }
    }
}
)();

(function() {
    if (!isLocationHrefContainsAll('echangyun', '/user/myCashFlow'))
        return;
    //================================================================
    // 002.长运网 支持双击明细记录自动录入到随手记
    //================================================================
    document.onclick = function() {
        //不要重置掉此Click事件,以便在翻页时局部刷新列表后,还能够支持绑定事件.
        //document.onclick = null;
        console.log("002.长运网 支持双击明细记录自动录入到随手记");
        var items = document.getElementById('form:dataTable').getElementsByTagName('tr');
        for (var i = 1; i < items.length; i++) {
            var item = items[i];
            item.ondblclick = function(e) {
                //====================================================================
                // 业务代码区
                //====================================================================
                var tr = getParentElementByTagName(e.srcElement, 'TR');
                var time = tr.children[0].innerText;
                var memo = tr.children[5].children[0].title;
                console.log(memo);

                if (memo.indexOf('本金') != -1) {
                    //从备注里提取出本金回款多少,利息多少.分别记录两笔记录.

                    //把本金入转账记录
                    var benJinRegex = new RegExp("本金：([\\d\\.]+)","gm");
                    var benjin = getNumber(benJinRegex, memo);
                    console.log('本金:' + benjin);

                    var category = "0";
                    var in_account = "24575940";
                    var out_account = "24575941";
                    var account = in_account + "-" + out_account;
                    var price = benjin;
                    saveTransferRecord(category, account, price, time, memo);

                    //把利息入收入记录
                    var liXiRegex = new RegExp("利息：([\\d\\.]+)","gm");
                    var liXi = getNumber(liXiRegex, memo);
                    console.log('利息:' + liXi);

                    var category = "175369647418";
                    var account = "24575940";
                    var price = liXi;
                    saveIncomeRecord(category, account, price, time, memo);
                } else if (memo.indexOf('手续费') != -1) {
                    //把手续费入账
                    var category = "346449535";
                    var account = "24575940";
                    var price = toNumber(tr.children[2].innerText) * -1;
                    savePayoutRecord(category, account, price, time, memo);
                } else {
                    showToastAtTitle('点击了不在预期范围内的行数据:' + tr.innerText);
                    console.log('点击了不在预期范围内的行数据:' + tr.innerText);
                    console.dir(tr);
                }
            }
        }
    }
}
)();

//================================================================
// 001.过滤0daydown不想看到的内容
//================================================================
(function() {
    if (!isLocationHrefContainsAll('0daydown'))
        return;
    if (!isLocationHrefContainsAll('page') && location.pathname.length > 1)
        return;

    window.ye = setInterval(document.ondblclick = function() {
        var blackList = ['场景', 'CAX', '网络技术', '素材', '摄影', '吉他', '音乐', '音色', '纹理', '模型', '教程'];

        function isInBlackList(txt) {
            for (var w in blackList)
                if (txt.indexOf(blackList[w]) > -1)
                    return true;
        }
        //检测所有的文章，将在黑名单内的文章取出来移除掉
        var items = document.getElementsByClassName('excerpt');
        var blackItems = [];
        for (var i = 0; i < items.length; i++) {
            var item = items[i];

            var header = item.getElementsByTagName('header')[0].innerText;
            if (!isInBlackList(header))
                continue;
            blackItems.push(item);
            //item.style.display = 'none';
        }

        //找到所有的评论区，移除掉。
        var comments = document.getElementsByClassName('d_comment')
        for (var i = 0; i < comments.length; i++)
            blackItems.push(comments[i]);

        //将所有不需要显示的内容移除掉。
        for (var i = 0; i < blackItems.length; i++)
            blackItems[i].parentElement.removeChild(blackItems[i]);

        if (blackItems.length > 0) {
            clearInterval(window.ye);
            if (document.oldTitle)
                document.title = document.oldTitle;
        } else {
            if (!document.oldTitle)
                document.oldTitle = document.title;
            showToastAtTitle('继续尝试中……');
        }
    }
    , 500);
}
)();
